package net.libra.ui
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.MouseEvent;
	import flash.text.TextField;
	
	import net.libra.ui.base.BaseGrid;
	import net.libra.ui.event.BaseEvent;

	/**
	 * 
	 * @author elvisjiang
	 * @data 2012-6-4
	 */	
	public class PageNavi extends EventDispatcher
	{
		private var _page:TextField;
		private var _prevBtn:EasyButton;
		private var _nextBtn:EasyButton;
		
		private var _baseGrid:BaseGrid;
		public function PageNavi(page:TextField,prevBtn:EasyButton,nextBtn:EasyButton)
		{
			_page = page;
			_page.text = "";
			_prevBtn = prevBtn;
			_nextBtn = nextBtn;
			_prevBtn.addEventListener(MouseEvent.CLICK,_click);
			_nextBtn.addEventListener(MouseEvent.CLICK,_click);
			
		}
		public function bindGrid(grid:BaseGrid):void
		{
			_baseGrid = grid;
			_baseGrid.addEventListener(BaseEvent.BASE_RENDER,_update);
			checkState();
		}
		protected function _update(event:BaseEvent):void
		{
			checkState();
		}
		private function checkState():void
		{
			if(_baseGrid.getCurrentPage() < _baseGrid.getTotalPages())
			{
				_nextBtn.setEnabled(true);
			}else{
				_nextBtn.setEnabled(false);
			}
			
			if(_baseGrid.getCurrentPage() <= 1)
			{
				_prevBtn.setEnabled(false);
			}else{
				_prevBtn.setEnabled(true);
			}
			_page.text = _baseGrid.getCurrentPage() + "/" + _baseGrid.getTotalPages();
		}
		
		protected function _click(event:MouseEvent):void
		{
			var currentPage:int = _baseGrid.getCurrentPage();
			if(event.target == _nextBtn)
			{
				currentPage ++;
			}else if(event.target == _prevBtn)
			{
				currentPage --;
			}
			_baseGrid.setCurrentPage(currentPage);
			dispatchEvent(new Event("FENYE"));
		}
		
		public function destory():void
		{
			_baseGrid.removeEventListener(BaseEvent.BASE_RENDER,_update);
			_baseGrid = null;
			_nextBtn.removeEventListener(MouseEvent.CLICK,_click);
			_nextBtn.destroy();
			_nextBtn = null;
			_prevBtn.removeEventListener(MouseEvent.CLICK,_click);
			_prevBtn.destroy();
			_prevBtn = null;
		}
	}
}